<template>
  <div class="loginDom">
    <div class="login-bg"></div>
    <div class="login-form">
      <a class="login-wx-switch" :class="{ 'switch_computer': showWich === 'login', 'switch_qr': showWich === 'qrCode' }"
        @click="qrOrLogin">
        <i class="switch"></i>
      </a>
      <h2 class="title">欢迎登录图图云平台</h2>
      <el-tabs v-model.trim="activeName" v-if="showWich === 'login'">
        <el-tab-pane label="密码登录" name="login">
          <el-form ref="loginForm" :model="loginForm" size="mini" :rules="loginRules">
            <el-form-item prop="username">
              <el-input v-model.trim.trim="loginForm.username" placeholder="手机号/邮箱/用户名"></el-input>
            </el-form-item>

            <el-form-item prop="password">
              <el-input v-model.trim="loginForm.password" type="password" placeholder="密码" show-password
                @keydown.enter.native="clickforgot"></el-input>
            </el-form-item>

            <el-form-item>
              <div class="flexCheck">
                <div>
                  <el-checkbox v-model.trim="loginForm.iskeep">
                  </el-checkbox>
                  <a class="agreement">记住登录名</a>
                </div>

              </div>
            </el-form-item>
            <el-button type="primary" class="primary" @click="clickforgot">登录</el-button>
          </el-form>
        </el-tab-pane>
        <el-tab-pane label="短信登陆" name="phoneLogin">
          <el-form ref="phoneForm" :model="phoneForm" size="mini" :rules="phoneRules">
            <el-form-item prop="phone">
              <el-input v-model.trim="phoneForm.phone" placeholder="手机号"></el-input>
            </el-form-item>

            <el-form-item prop="verification" class="parent">
              <!-- style="width: 50%;" -->
              <el-input v-model.trim="phoneForm.verification" placeholder="请输入验证码" />
              <el-button class="verify-btn" type="primary" @click="validationText">{{ validation }}</el-button>
            </el-form-item>
            <!-- 滑动解锁 -->
            <div class="jc-component__range">
              <div class="jc-range" :class="rangeStatus ? 'success' : ''">
                <i @mousedown="rangeMove" :class="rangeStatus ? successIcon : startIcon"></i>
                {{ rangeStatus ? successText : startText }}
              </div>
            </div>

            <el-button type="primary" class="primary" @click="clickPhone">登录</el-button>
          </el-form>

        </el-tab-pane>
      </el-tabs>
      <div class="qr-Code" v-else>
        <div>请使用微信扫描二维码登录</div>
        <div class="qr">
          <div id="login_container" style="height: 100%; width: 100%"></div>
        </div>
      </div>
      <div class="clues">
        <div>还没有账号？
          <span class="blue" @click="showForgot('register')">去注册</span>
        </div>
        <div class="blue" @click="showForgot('forgotPassword')">忘记密码？</div>
      </div>
    </div>
    <el-dialog title="友情提示！" :visible.sync="dialogVisible" width="25%" :close-on-click-modal="false"
      :close-on-press-escape="false" v-dialogDrag>
      <span>该微信号还未绑定平台账号，为便于您下次登入，您可登入平台，前往【个人中心-安全设置】 进行绑定。</span>
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" size="small" @click="gotoLogin">已有账户,去登录</el-button>
        <el-button size="small" @click="gotoRegister">新用户注册</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import sliding from '@/utils/login/sliding'
import { getVerificationPhoneRequest, submitSMSLoginRequest, getWeChatRequest, getWeChatConfigRequest } from '@/api/login'
import { deepClone } from '@/utils';

export default {
  name: 'BaiaoweifanUiLogin',
  mixins: [sliding],
  data() {
    return {
      //微信二维码配置
      wxConfig: null,
      dialogVisible: false,
      showWich: 'login',
      activeName: 'login',
      //登录
      loginForm: {
        username: '',
        password: '',
        iskeep: false,
      },
      loginRules: {
        username: [
          { required: true, message: '请输入账号', trigger: 'blur' },
        ],
        password: [
          { required: true, message: '请输入密码', trigger: 'blur' }
        ],
      },
      phoneForm: {
        phone: '',
        verification: ''
      },
      phoneRules: {
        phone: [
          { required: true, message: '请输入手机号', trigger: 'blur' },
          { pattern: /^1[3456789]\d{9}$/, message: '请输入正确的手机号码', trigger: ['blur'] }
        ],
        verification: [
          { required: true, message: '请输入验证码', trigger: 'blur' }
        ],
      },
      validation: '发送验证码',
      countdown: 60,
      flag: true,
    };
  },
  created() {
    this.init()
  },
  async mounted() {
    //监听单个事件
    window.addEventListener('message', async (msg) => {
      if (msg.data.code && msg.data.state && this.flag) {
        const res = await getWeChatRequest(msg.data)
        if (res.code === 1003) {
          this.flag = true
          this.$message.error(res.message)
          this.dialogVisible = true
        } else if (res.code === 200) {
          this.flag = false
          this.$store.dispatch('login/weChatLogin', res.data)
        } else {
          this.flag = true
        }
      }
    })
    const res = await getWeChatConfigRequest()
    if (res.code !== 200) this.$message.error('系统异常，请联系管理员！')
    this.wxConfig = res.data
  },
  methods: {
    init() {
      let userInfo = JSON.parse(localStorage.getItem('username'))
      if (userInfo) {
        this.loginForm = userInfo
        this.phoneForm.phone = userInfo.username
      } else {
        this.loginForm = {
          username: '',
          password: '',
          iskeep: false,
        }
      }
    },
    showForgot(value) {
      this.$emit('showForgot', value)
    },
    //账密登录
    clickforgot() {
      //是否记住登录名
      if (this.loginForm.iskeep) {
        let obj = deepClone(this.loginForm)
        obj.password = ''
        localStorage.setItem('username', JSON.stringify(obj))
      } else {
        localStorage.clear()
      }
      this.$refs['loginForm'].validate(res => {
        if (!res) return
        const data = {
          loginAccount: this.loginForm.username,
          loginPassword: this.loginForm.password,
        }
        this.$store.dispatch('login/passwordLogin', data)
      })
    },
    //验证码校验
    validationText() {
      if (!this.timer) {
        this.$refs['phoneForm'].validateField(['phone'], async err => {
          if (!err) {

            try {
              //发请求
              const res = await getVerificationPhoneRequest({ mobilePhone: this.phoneForm.phone })
              if (res.code !== 200) return this.$message({
                message: res.message,
                type: 'warning'
              })
              this.validation = `60s后重新发送`;
              this.timer = setInterval(() => {
                if (this.countdown > 0 && this.countdown <= 60) {
                  this.countdown--;
                  if (this.countdown !== 0) {
                    this.validation = `${this.countdown}s后重新发送`;
                  } else {
                    clearInterval(this.timer);
                    this.validation = "重新发送";
                    this.countdown = 60;
                    this.timer = null;
                    this.codeDisabled = false;
                  }
                }
              }, 1000)
            } catch (error) {
              this.$message.error('系统错误，请联系管理员！')
            }
          }
        })
      }
    },
    //手机登录
    clickPhone() {
      this.$refs['phoneForm'].validate(async res => {
        if (res) {
          if (!this.rangeStatus) return this.$message({
            showClose: true,
            message: '请拖动滑块到最右边',
            type: 'warning'
          });
          const data = {
            mobilePhone: this.phoneForm.phone,
            validCode: this.phoneForm.verification
          }
          this.$store.dispatch('login/phoneLogin', data)
        }
      })
    },
    qrOrLogin() {
      if (this.showWich === 'login') {
        this.showWich = 'qrCode'
        this.$nextTick(() => {
          //css内容
          const { appid, redirectUri } = this.wxConfig
          var content = ".impowerBox .qrcode {width: 200px;} .impowerBox .title {display: none;} .impowerBox .info {width: 200px;display: none;} .status_icon {display: none}";
          //记住一定要注明文件类型是css
          var blob = new Blob([content], { type: "text/css;charset=utf-8" });
          var reader = new FileReader();
          const herf = redirectUri + '/login_code'
          reader.readAsDataURL(blob);
          reader.onload = function (e) {
            var wxqrcode = new WxLogin({
              self_redirect: true, //true将页面跳转放在ifream里面   false直接跳转到要跳转的页面
              id: "login_container",
              appid: appid,
              scope: "snsapi_login",
              redirect_uri: encodeURIComponent(herf),
              href: this.result,//data:text/css;charset=utf-8;base64,LmltcG93ZXJCb3ggLnFyY29kZSB7d2lkdGg6IDIwMHB4O30uaW1wb3dlckJveCAudGl0bGUge2Rpc3BsYXk6IG5vbmU7fS5pbXBvd2VyQm94IC5pbmZvIHt3aWR0aDogMjAwcHg7fQ==
              state: Math.ceil(Math.random() * 1000),//为了防止csrf（跨站请求伪造攻击），设置一个3位的随机数
              style: "black",
            });
          };
        });
      } else {
        this.showWich = 'login'
      }
    },
    gotoLogin() {
      this.dialogVisible = false
      this.showWich = 'login'
    },
    gotoRegister() {
      this.dialogVisible = false
      this.showForgot('register')
    }
  },
};
</script>


<style lang="scss" scoped>
@import "~@/styles/variables.scss";
$bg: #fff;



.qr-Code {
  text-align: center;

  p {
    color: #666;
    font-size: 15px;
  }

  .qr {
    // width: 230px;
    // height: 330px;
    margin: 30px auto;
    overflow: hidden !important;
    // border: 1px solid #ccc;
  }
}

.loginDom {
  display: flex;

  .login-bg {
    width: 528px;
    height: 533px;
    // background: url(../../../assets/big.png) no-repeat 50%;
    background-size: cover;
    position: absolute;
    top: 20%;
    right: 55%;
  }

  ::v-deep.el-tabs__header {
    margin: 0 0 20px;
  }

  .flexCheck {
    display: flex;
    font-size: 13px;
    margin-top: 10px;
    justify-content: space-between;

    .agreement {
      margin-left: 8px;
    }
  }

  .primary {
    background: linear-gradient(90deg, $themeTopToolColor, $themeTopToolColor);
    width: 83%;
    height: 48px;
    border-radius: 24px;
    border: 0;
    font-size: 20px;
    position: fixed;
    bottom: 18%;
    left: 50%;
    transform: translateX(-50%);

    &:hover {
      background: linear-gradient(90deg, $themeTopToolColor, $themeTopToolColor);
    }
  }
}

.clues {
  width: 350px;
  display: flex;
  justify-content: space-between;
  align-items: center;
  // color: #ccc;
  font-size: 13px;
  position: fixed;
  bottom: 9%;
  text-align: center;

  .blue {
    cursor: pointer;
    color: $themeTopToolColor;
  }

  // div{
  //   width: 46px;
  //   height: 1px;
  //   background-color: #ccc;
  // }
}

::v-deep .login-form {
  position: absolute;
  top: 50%;
  right: 18%;
  transform: translateY(-50%);
  border-radius: 15px;
  background: $bg;
  width: 350px;
  padding: 35px 35px 15px 35px;
  box-sizing: content-box;
  height: 500px !important;
  max-height: 700px;

  .title {
    font-weight: 400;
    margin-bottom: 40px;
  }

  .el-input {
    height: 40px;

    input {
      height: 40px;

      //   margin-top: 5%;
      &::placeholder {
        color: #666;
        font-size: 15px;
      }
    }
  }

  .login-wx-switch {
    display: block;
    width: 60px;
    height: 60px;
    border-radius: 6px;
    position: fixed;
    background-color: $themeTopToolColor;
    top: 4px;
    right: 4px;

    background-repeat: no-repeat;
    background-size: 35px;
    background-position: 17px 8px;

    &.switch_qr {
      background-image: url(../../../assets/computer.png);
    }

    &.switch_computer {
      background-image: url(../../../assets/qr.png);
    }

    .switch {
      display: block;
      width: 60px;
      height: 60px;
      background: linear-gradient(225deg, transparent 40px, #fff 0);
    }

  }

  .input-icon {
    width: 14px;
    margin-left: 2px;
  }

  .el-input__prefix {
    line-height: 50px;
    left: 15px;
  }

  .el-input--prefix .el-input__inner {
    padding-left: 38px;
  }

  .parent {
    position: relative;

    .verify-btn {
      // background: linear-gradient(90deg, $themeTopToolColor, $themeTopToolColor);
      background-color: transparent;
      position: absolute;
      top: 0;
      right: 0;
      border: 0;
      color: $themeTopToolColor;
      float: right;
      font-weight: 700;
      height: 40px;
      border-radius: 5px;
      width: 125px;
    }
  }
}

::v-deep .el-form-item--mini .el-form-item__content {
  height: 46px;
}

//滑动
@mixin jc-flex {
  display: flex;
  justify-content: center;
  align-items: center;
}

.jc-component__range {
  .jc-range {
    background-color: #e9e9e9;
    position: relative;
    transition: 1s all;
    user-select: none;
    color: #585858;
    @include jc-flex;
    height: 38px;

    /*no*/
    &.success {
      background-color: $themeTopToolColor;
      color: #fff;

      i {
        color: $themeTopToolColor;
      }
    }

    i {
      position: absolute;
      left: 0;
      width: 38px;
      /*no*/
      height: 100%;
      color: $themeTopToolColor;
      background-color: #fff;
      border: 1px solid #d8d8d8;
      cursor: pointer;
      font-size: 24px;
      @include jc-flex;
    }
  }
}
</style>
